<?php

namespace app\v1\controller;

use app\model\BizGoodsModel;
use support\Request;
use app\model\Util;
use EasyWeChat\Factory;
use support\Log;
use app\model\BizGoodsOrderModel;
use app\model\BizModel;
use app\model\BizGoodsTicketModel;
use app\model\BizAdminModel;
use app\model\RefundRecordModel;
use app\model\ComplaintModel;
use \Exception;
use app\model\BizPayRecordModel;
class BizGoodsOrderController {
    

    public function detail(Request $request){
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new \Exception('订单ID不能为空');
            }

            $order = BizGoodsOrderModel::find($id);
            if (!$order) {
                throw new \Exception('订单不存在');
            }

            // 获取商品信息
            $goods = BizGoodsModel::find($order->biz_goods_id);
            if (!$goods) {
                throw new \Exception('商品信息不存在');
            }

            // 获取商家信息
            $biz = BizModel::find($order->biz_id);
            if (!$biz) {
                throw new \Exception('商家信息不存在');
            }

            // 获取核销码信息
            $tickets = BizGoodsTicketModel::where('order_id', $id)
                // ->where('status', 0) // 未使用
                // ->where('expired_at', '>', time()) // 未过期
                ->get();

            // 构建返回数据
            $data = [
                'order' => [
                    'id' => $order->id,
                    'money' => $order->money,
                    'status' => BizGoodsOrderModel::STATUS[$order->status],
                    'quantity' => $order->quantity,
                    'phone' => $order->phone,
                    'created_at' => date('Y-m-d H:i:s', $order->created_at),
                    'paid_at' => date('Y-m-d H:i:s', $order->paid_at),
                    'transaction_id' => $order->transaction_id,
                    'out_trade_no' => $order->out_trade_no
                ],
                'goods' => [
                    'id' => $goods->id,
                    'title' => $goods->title,
                    'image' => Util::pathToUrl($goods->image),
                    'price' => $goods->price,
                    'description' => $goods->description
                ],
                'biz' => [
                    'id' => $biz->id,
                    'name' => $biz->name,
                    'image' => Util::pathToUrl($biz->avatar),
                    'phone' => $biz->biz_phone,
                    'address' => $biz->shop_address,
                    'service' => $biz->formatService()
                ],
                'tickets' => $tickets->map(function($ticket) {
                    return [
                        'id' => $ticket->id,
                        'code' => $ticket->code,
                        'status' => $ticket->status,
                        'status_text' => BizGoodsTicketModel::STATUS_TEXT[$ticket->status],
                        'expired_at' => $ticket->expired_at < time(),
                        'expired_at_txt' => date('Y-m-d H:i:s', $ticket->expired_at)
                    ];
                })->toArray()
            ];

            return json([
                'code' => 1,
                'msg' => '获取订单详情成功',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    /**
     * 检查核销码是否合规以及当前用户是否有权核销
     * @param \support\Request $request
     * @return \support\Response
     */
    public function checkTicket(Request $request){
        $user = $request->userLogin;
        $code = $request->get('code');
        $ticket = BizGoodsTicketModel::where('code', $code)->first();
        if (!$ticket) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '核销码不存在'
            ]);
        }

        // 检查核销码是否合规
        if ($ticket->status != 0) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '核销码已使用'
            ]);
        }

        // 检查当前用户是否有权核销
        $admin = BizAdminModel::where('user_id', $user->id)->where('biz_id', $ticket->biz_id)->first();
        if (!$admin) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '当前用户无权核销'
            ]);
        }

        // 检查核销码是否过期
        if ($ticket->expired_at < time() || $ticket->status == 1) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '核销码已过期'
            ]);
        }

        $goods = BizGoodsModel::find($ticket->goods_id);
        if (!$goods) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '商品不存在'
            ]);
        }

        $order = BizGoodsOrderModel::where('id', $ticket->order_id)->first();
        if (!$order) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '订单不存在'
            ]);
        }

        $biz = BizModel::find($ticket->biz_id);
        if (!$biz) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '商家不存在'
            ]);
        }

        $data = [
            'ticket_id' => $ticket->id,
            'goods_id' => $goods->id,
            'goods_title' => $goods->title,
            'biz_name' => $biz->name,
            'created_at' => date('Y-m-d H:i:s', $order->created_at),
            'expired_at' => date('Y-m-d H:i:s', $ticket->expired_at),
            'phone' => $order->phone,
            'status' => $ticket->status,
            'used_at' => date('Y-m-d H:i:s', $ticket->used_at),
        ];

        return json([
            'code' => 1,
            'isError' => false,
            'msg' => '核销码存在',
            'data' => $data
        ]);
    }

    public function refundTicket(Request $request){
        $user = $request->userLogin;
        $input = $request->post('data');
        $ticket = BizGoodsTicketModel::where('id', $input['id'])->first();
        if (!$ticket) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '核销码不存在'     
            ]);
        }

        $order = BizGoodsOrderModel::where('id', $ticket->order_id)->first();
        if (!$order) {
            return json([
                'code' => 1,
                'isError' => true,
                'msg' => '订单不存在'   
            ]);
        }

        $refundRecord = new RefundRecordModel();
        $refundRecord->type = 'biz-order';
        $refundRecord->item_id = $ticket->id;
        $refundRecord->refund_amount = $ticket->money;
        $refundRecord->refund_at = 0;
        $refundRecord->status = 'doing';
        $refundRecord->created_at = time();
        $refundRecord->updated_at = time();
        $refundRecord->save();

        // 退款中
        $ticket->status = 2;
        $ticket->save();

        return json([
            'code' => 1,    
            'isError' => false,
            'msg' => '退款成功'
        ]);
    }   

    
    public function complaint(Request $request)
    {
        try {
            $user = $request->userLogin;
            $input = $request->post();
            $orderId = $input['order_id'];
            $content = $input['content'];
            $type = $input['type'];

            if (empty($orderId) || empty($content)) {
                throw new \Exception('订单ID和投诉内容不能为空');
            }

            if(in_array($type, ['biz-order', 'biz-pay','store-order']) == false){
                throw new \Exception('投诉类型错误');
            }

            // 检查订单是否存在
            if($type == 'biz-order'){
                $order = BizGoodsOrderModel::find($orderId);
                if (!$order) {
                    throw new \Exception('订单不存在');
                }
            }else if($type == 'biz-pay'){
                $order = BizPayRecordModel::find($orderId);
                if (!$order) {
                    throw new \Exception('订单不存在');
                }
            }
            

            // 写入投诉
            $complaint = new ComplaintModel();
            $complaint->user_id = $user->id;
            $complaint->item_id = $orderId;
            $complaint->type = $type;
            $complaint->content = $content;
            $complaint->created_at = time();
            $complaint->updated_at = time();
            $complaint->save();

            return json([
                'code' => 1,
                'msg' => '投诉提交成功',
                'data' => null
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    //get-order-list-by-biz
    public function getOrderListByBiz(Request $request){
        try {
            $user = $request->userLogin;
            $page = $request->get('page', 1);
            $limit = $request->get('limit', 10);

            $bizAdmin = BizAdminModel::where('user_id', $user->id)->first();
            if (!$bizAdmin) {
                throw new \Exception('当前用户无权获取订单列表');
            }

            $offset = ($page - 1) * $limit;

            $query = BizGoodsOrderModel::with(['bizGoods', 'biz'])
                ->where('biz_id', $bizAdmin->biz_id)
                ->whereNull('deleted_at')
                ->where('status', '=','pay')
                ->orderBy('created_at', 'desc');

            // 获取总数
            $total = $query->count();

            // 获取分页数据
            $orders = $query->offset($offset)->limit($limit)->get();

            $orderList = [];
            foreach ($orders as $order) {
                $orderData = [
                    'id' => $order->id,
                    'quantity' => $order->quantity,
                    'phone' => $order->phone ? (mb_substr($order->phone, 0, 3) . '****' . mb_substr($order->phone, -4)) : '',
                    'price' => round($order->price, 2), // 单价
                    'money' => round($order->money, 2), // 差价金额
                    'pay_money' => round($order->pay_money, 2), // 实付金额
                    'status' => $order->status,
                    'status_text' => $this->getOrderStatusText($order->status),
                    'created_at' => $order->created_at,
                    'created_at_text' => date('Y-m-d H:i:s', $order->created_at),
                    'paid_at' => $order->paid_at,
                    'paid_at_text' => $order->paid_at ? date('Y-m-d', $order->paid_at) : '',
                    'transaction_id' => $order->transaction_id,
                    'out_trade_no' => $order->out_trade_no,
                    'expired_at' => $order->expired_at,
                    'ping_id' => $order->ping_id,
                    'trade_no' => $order->trade_no,
                    'expired_at_text' => $order->expired_at ? date('Y-m-d', $order->expired_at) : '',
                ];

                // 添加商品信息
                if ($order->bizGoods) {
                    $orderData['goods_title'] = $order->bizGoods->title;
                    $orderData['goods_image'] = Util::pathToUrl($order->bizGoods->image);
                    $orderData['goods_price'] = round($order->bizGoods->price, 2);
                } else {
                    $orderData['goods_title'] = '商品已删除';
                    $orderData['goods_image'] = '';
                    $orderData['goods_price'] = 0;
                }

                $orderList[] = $orderData;
            }

            // 计算是否有更多数据
            $hasMore = ($offset + $limit) < $total;

            return json([
                'code' => 1,
                'data' => [
                    'list' => $orderList,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'has_more' => $hasMore
                ],
                'msg' => '获取消费订单列表成功'
            ]);
        }catch(Exception $e){
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }

    private function getOrderStatusText($status)
    {
        $statusMap = [
            'unpay' => '待支付',
            'pay' => '已支付'
        ];

        return $statusMap[$status] ?? '未知状态';
    }

    public function doHide(Request $request){
        $user = $request->userLogin;
        $id = $request->post('id');
        
        try {
            $order = BizGoodsOrderModel::find($id);
            if (!$order) {
                throw new Exception('订单不存在');
            }
    
            if($order->user_id != $user['id']){
                throw new Exception('当前用户无权隐藏订单');
            }
    
            $order->hide_at = time();
            $order->save();
    
            return json([
                'code' => 1
            ]);
        }catch(Exception $e){
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
        
    }

}
